<template>
  <div class="table-columns-panel">
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-sm font-medium text-gray-700">列定义</h3>
      <div class="flex space-x-2">
        <el-button-group class="mr-2">
          <el-button 
            size="small" 
            :disabled="selectedColumnIndex <= 0 || selectedColumnIndex === -1" 
            @click="moveColumnUp" 
            type="primary" 
            plain
            class="hover:bg-blue-50 transition-colors"
          >
            <el-icon><ArrowUp /></el-icon>
          </el-button>
          <el-button 
            size="small" 
            :disabled="selectedColumnIndex === -1 || selectedColumnIndex >= localColumns.length - 1" 
            @click="moveColumnDown" 
            type="primary" 
            plain
            class="hover:bg-blue-50 transition-colors"
          >
            <el-icon><ArrowDown /></el-icon>
          </el-button>
        </el-button-group>
        <el-button size="small" @click="addColumn" type="success" plain class="hover:bg-green-50 transition-colors">
          <el-icon><Plus /></el-icon>添加列
        </el-button>
      </div>
    </div>

    <!-- 添加外层包装，控制表格容器 -->
    <div class="table-wrapper border border-gray-200 rounded-lg shadow-sm">
      <!-- 设置固定高度并启用横向滚动 -->
      <div class="overflow-x-auto" style="max-height: calc(100vh - 280px);">
        <table class="table-fixed min-w-max divide-y divide-gray-200">
          <thead class="bg-gray-50 sticky top-0 z-10">
            <tr>
              <th class="w-12 px-2 py-3 text-left bg-gray-50"></th>
              <th class="w-40 px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left bg-gray-50">列名</th>
              <th class="w-56 px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left bg-gray-50">数据类型</th>
              <th class="w-32 px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left bg-gray-50">长度/值</th>
              <th class="w-20 px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-center bg-gray-50">不为空</th>
              <th class="w-20 px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-center bg-gray-50">主键</th>
              <th class="w-20 px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-center bg-gray-50">
                {{ autoIncrementLabel }}
              </th>
              <th class="w-40 px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left bg-gray-50">默认值</th>
              <th class="w-56 px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left bg-gray-50">注释</th>
              <th class="w-16 px-3 py-3 text-left bg-gray-50"></th>
            </tr>
          </thead>
          <tbody id="columnsTableBody" class="bg-white divide-y divide-gray-200">
            <tr v-for="(column, index) in localColumns" :key="index" 
                :class="{ 'bg-blue-50': selectedColumnIndex === index }"
                class="hover:bg-gray-50 transition-colors cursor-pointer"
                :data-index="index"
                @click="selectColumn(index)">
              <td class="w-12 px-2 py-3">
                <div class="drag-handle w-4 h-6 mx-auto flex flex-col justify-center items-center cursor-move">
                  <div class="w-4 h-0.5 bg-gray-300 mb-1"></div>
                  <div class="w-4 h-0.5 bg-gray-300 mb-1"></div>
                  <div class="w-4 h-0.5 bg-gray-300"></div>
                </div>
              </td>
              <td class="w-40 px-3 py-3">
                <el-input v-model="column.name" size="small" placeholder="列名" @change="handleColumnChange" 
                  class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all" />
              </td>
              <td class="w-56 px-3 py-3">
                <el-select v-model="column.type" size="small" style="width: 100%" @change="(val) => handleDataTypeChange(val, index)"
                  class="data-type-select hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all">
                  <el-option-group 
                    v-for="(group, groupName) in dataTypeGroups" 
                    :key="groupName" 
                    :label="groupName"
                  >
                    <el-option 
                      v-for="type in group" 
                      :key="type.value" 
                      :label="type.label" 
                      :value="type.value"
                    />
                  </el-option-group>
                </el-select>
              </td>
              <td class="w-32 px-3 py-3">
                <el-input 
                  v-if="needsLength(column.type)" 
                  v-model="column.length" 
                  size="small" 
                  placeholder="长度" 
                  @change="handleColumnChange" 
                  class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
                />
                <el-input 
                  v-else-if="needsValues(column.type)" 
                  v-model="column.values" 
                  size="small" 
                  placeholder="值,用逗号分隔" 
                  @change="handleColumnChange"
                  class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
                />
                <span v-else class="text-gray-400 text-xs">-</span>
              </td>
              <td class="w-20 px-3 py-3 text-center">
                <el-checkbox v-model="column.notNull" @change="handleColumnChange" 
                  class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all" />
              </td>
              <td class="w-20 px-3 py-3 text-center">
                <el-checkbox v-model="column.primaryKey" @change="() => handlePrimaryKeyChange(index)" 
                  class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all" />
              </td>
              <td class="w-20 px-3 py-3 text-center">
                <el-checkbox 
                  v-if="databaseType !== 'postgresql'"
                  v-model="column.autoIncrement" 
                  :disabled="!canBeAutoIncrement(column.type)" 
                  @change="() => handleAutoIncrementChange(index)" 
                  class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
                />
                <el-checkbox 
                  v-else-if="isSerialType(column.type)"
                  :model-value="true" 
                  disabled
                />
                <span v-else class="text-gray-400 text-xs">-</span>
              </td>
              <td class="w-40 px-3 py-3">
                <el-input v-model="column.defaultValue" size="small" placeholder="默认值" @change="handleColumnChange" 
                  class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all" />
              </td>
              <td class="w-56 px-3 py-3">
                <el-input 
                  v-model="column.comment" 
                  size="small" 
                  placeholder="注释" 
                  @change="handleColumnChange" 
                  class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
                />
              </td>
              <td class="w-16 px-3 py-3">
                <el-button 
                  type="danger" 
                  size="small" 
                  circle 
                  plain
                  @click="confirmRemoveColumn(index)"
                  class="hover:bg-red-50 transition-colors"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 如果是达梦数据库且是字符类型，添加语义类型选择 -->
    <template v-if="databaseType === 'dameng' && selectedColumnIndex !== -1 && isCharType(localColumns[selectedColumnIndex].type)">
      <div class="mt-3 flex items-center text-xs justify-center">
        <span class="text-gray-500 mr-2">长度语义:</span>
        <el-radio-group 
          v-model="localColumns[selectedColumnIndex].semanticType" 
          size="small" 
          @change="handleColumnChange"
        >
          <el-radio label="BYTE">字节</el-radio>
          <el-radio label="CHAR">字符</el-radio>
        </el-radio-group>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { Plus, Delete, ArrowUp, ArrowDown } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import Sortable from 'sortablejs';
import { 
  parseColumnLength, 
  parseColumnComment, 
  getColumnSemanticType,
  isCharType as checkCharType,
  createUnifiedColumnModel
} from '@/utils/dbColumnParser';

const props = defineProps({
  columns: {
    type: Array,
    default: () => []
  },
  databaseType: {
    type: String,
    default: 'mysql'
  }
});

const emit = defineEmits(['update', 'add', 'remove']);

const localColumns = ref([...props.columns]);
const selectedColumnIndex = ref(-1);
let sortableInstance = null;

// 监听props变化
watch(() => props.columns, (newColumns) => {
  localColumns.value = [...newColumns];
  standardizeColumns();
}, { deep: true });

// 标准化列数据
const standardizeColumns = () => {
  console.log('[DEBUG] 原始列数据:', JSON.stringify(localColumns.value, null, 2));
  
  localColumns.value = localColumns.value.map(col => {
    // 从显示值初始化实际长度值（针对达梦数据库）
    if (props.databaseType === 'dameng' && col.lengthDisplay && !col.length) {
      console.log(`[DEBUG] 从lengthDisplay初始化length: ${col.name} - ${col.lengthDisplay}`);
      // 处理可能的"precision,scale"格式
      if (col.lengthDisplay.includes(',')) {
        col.length = col.lengthDisplay.split(',')[0];
      } else {
        col.length = col.lengthDisplay;
      }
    }
    
    const standardized = createUnifiedColumnModel(col, props.databaseType);
    return standardized;
  });
  
  console.log('[DEBUG] 标准化后列数据:', JSON.stringify(localColumns.value, null, 2));
};

// 初始化排序功能
onMounted(() => {
  standardizeColumns();
  initSortable();
});

// 组件销毁前清理
onBeforeUnmount(() => {
  if (sortableInstance) {
    sortableInstance.destroy();
    sortableInstance = null;
  }
});

// 初始化Sortable
const initSortable = () => {
  // 确保排序实例不重复创建
  if (sortableInstance) {
    sortableInstance.destroy();
    sortableInstance = null;
  }

  // 获取表体DOM元素
  const el = document.getElementById('columnsTableBody');
  if (!el) {
    console.error('Table body element not found');
    return;
  }

  // 创建Sortable实例
  sortableInstance = new Sortable(el, {
    handle: '.drag-handle',       // 拖动手柄选择器
    animation: 150,               // 动画速度（毫秒）
    ghostClass: 'bg-blue-100',    // 拖动时"幽灵"元素的类
    chosenClass: 'bg-blue-50',    // 选中元素的类
    dragClass: 'opacity-70',      // 拖动中元素的类
    
    // 禁用拖拽时Form元素的交互
    onChoose: function() {
      document.body.classList.add('sorting-active');
    },
    
    onUnchoose: function() {
      document.body.classList.remove('sorting-active');
    },
    
    // 拖拽结束时更新数据
    onEnd: function(evt) {
      // 防止意外触发
      if (evt.oldIndex === evt.newIndex) return;
      
      // 更新内部数据模型
      const movedItem = localColumns.value.splice(evt.oldIndex, 1)[0];
      localColumns.value.splice(evt.newIndex, 0, movedItem);
      
      // 通知父组件数据已更新
      handleColumnChange();
    }
  });
  
  console.log('Sortable initialized on table body:', el);
};

// 重新初始化排序
const reinitSortable = () => {
  setTimeout(() => {
    initSortable();
  }, 200);
};

// 监听列数变化，重新初始化排序
watch(() => localColumns.value.length, reinitSortable);

// 监听列的类型变化，确保DOM更新后重新初始化排序
watch(() => localColumns.value.map(col => col.type), reinitSortable, { deep: true });

// 根据数据库类型获取数据类型分组
const dataTypeGroups = computed(() => {
  switch (props.databaseType) {
    case 'mysql':
      return {
        '数值类型': [
          { label: 'TINYINT', value: 'tinyint' },
          { label: 'SMALLINT', value: 'smallint' },
          { label: 'MEDIUMINT', value: 'mediumint' },
          { label: 'INT', value: 'int' },
          { label: 'BIGINT', value: 'bigint' },
          { label: 'DECIMAL', value: 'decimal' },
          { label: 'FLOAT', value: 'float' },
          { label: 'DOUBLE', value: 'double' }
        ],
        '文本类型': [
          { label: 'CHAR', value: 'char' },
          { label: 'VARCHAR', value: 'varchar' },
          { label: 'TINYTEXT', value: 'tinytext' },
          { label: 'TEXT', value: 'text' },
          { label: 'MEDIUMTEXT', value: 'mediumtext' },
          { label: 'LONGTEXT', value: 'longtext' }
        ],
        '日期和时间类型': [
          { label: 'DATE', value: 'date' },
          { label: 'TIME', value: 'time' },
          { label: 'DATETIME', value: 'datetime' },
          { label: 'TIMESTAMP', value: 'timestamp' },
          { label: 'YEAR', value: 'year' }
        ],
        '其他类型': [
          { label: 'JSON', value: 'json' },
          { label: 'BINARY', value: 'binary' },
          { label: 'VARBINARY', value: 'varbinary' },
          { label: 'BLOB', value: 'blob' },
          { label: 'ENUM', value: 'enum' },
          { label: 'SET', value: 'set' }
        ]
      };
    case 'postgresql':
      return {
        '整数类型': [
          { label: 'SMALLINT', value: 'smallint' },
          { label: 'INTEGER', value: 'integer' },
          { label: 'BIGINT', value: 'bigint' },
          { label: 'SERIAL', value: 'serial' },
          { label: 'SMALLSERIAL', value: 'smallserial' },
          { label: 'BIGSERIAL', value: 'bigserial' }
        ],
        '小数类型': [
          { label: 'DECIMAL', value: 'decimal' },
          { label: 'NUMERIC', value: 'numeric' },
          { label: 'REAL', value: 'real' },
          { label: 'DOUBLE PRECISION', value: 'double precision' },
          { label: 'MONEY', value: 'money' }
        ],
        '字符类型': [
          { label: 'CHARACTER', value: 'character' },
          { label: 'VARCHAR', value: 'varchar' },
          { label: 'TEXT', value: 'text' }
        ],
        '日期时间类型': [
          { label: 'DATE', value: 'date' },
          { label: 'TIME', value: 'time' },
          { label: 'TIMESTAMP', value: 'timestamp' },
          { label: 'INTERVAL', value: 'interval' }
        ],
        '其他类型': [
          { label: 'BOOLEAN', value: 'boolean' },
          { label: 'BYTEA', value: 'bytea' },
          { label: 'UUID', value: 'uuid' },
          { label: 'JSON', value: 'json' },
          { label: 'JSONB', value: 'jsonb' },
          { label: 'ARRAY', value: 'array' }
        ]
      };
    case 'sqlite':
      return {
        '基本类型': [
          { label: 'INTEGER', value: 'integer' },
          { label: 'REAL', value: 'real' },
          { label: 'TEXT', value: 'text' },
          { label: 'BLOB', value: 'blob' },
          { label: 'NUMERIC', value: 'numeric' }
        ],
        '附加类型': [
          { label: 'VARCHAR', value: 'varchar' },
          { label: 'CHAR', value: 'char' },
          { label: 'DATE', value: 'date' },
          { label: 'DATETIME', value: 'datetime' },
          { label: 'BOOLEAN', value: 'boolean' }
        ]
      };
    case 'sqlserver':
      return {
        '精确数值类型': [
          { label: 'BIT', value: 'bit' },
          { label: 'TINYINT', value: 'tinyint' },
          { label: 'SMALLINT', value: 'smallint' },
          { label: 'INT', value: 'int' },
          { label: 'BIGINT', value: 'bigint' },
          { label: 'DECIMAL', value: 'decimal' },
          { label: 'NUMERIC', value: 'numeric' },
          { label: 'MONEY', value: 'money' },
          { label: 'SMALLMONEY', value: 'smallmoney' }
        ],
        '近似数值类型': [
          { label: 'FLOAT', value: 'float' },
          { label: 'REAL', value: 'real' }
        ],
        '字符类型': [
          { label: 'CHAR', value: 'char' },
          { label: 'VARCHAR', value: 'varchar' },
          { label: 'TEXT', value: 'text' },
          { label: 'NCHAR', value: 'nchar' },
          { label: 'NVARCHAR', value: 'nvarchar' },
          { label: 'NTEXT', value: 'ntext' }
        ],
        '日期时间类型': [
          { label: 'DATE', value: 'date' },
          { label: 'TIME', value: 'time' },
          { label: 'DATETIME', value: 'datetime' },
          { label: 'DATETIME2', value: 'datetime2' },
          { label: 'SMALLDATETIME', value: 'smalldatetime' },
          { label: 'DATETIMEOFFSET', value: 'datetimeoffset' }
        ],
        '其他类型': [
          { label: 'BINARY', value: 'binary' },
          { label: 'VARBINARY', value: 'varbinary' },
          { label: 'IMAGE', value: 'image' },
          { label: 'XML', value: 'xml' },
          { label: 'JSON', value: 'json' },
          { label: 'UNIQUEIDENTIFIER', value: 'uniqueidentifier' }
        ]
      };
    case 'dameng':
      return {
        '数值类型': [
          { label: 'INT', value: 'int' },
          { label: 'INTEGER', value: 'integer' },
          { label: 'BIGINT', value: 'bigint' },
          { label: 'SMALLINT', value: 'smallint' },
          { label: 'TINYINT', value: 'tinyint' },
          { label: 'DECIMAL', value: 'decimal' },
          { label: 'NUMBER', value: 'number' },
          { label: 'FLOAT', value: 'float' },
          { label: 'DOUBLE', value: 'double' }
        ],
        '字符类型': [
          { label: 'CHAR', value: 'char' },
          { label: 'VARCHAR', value: 'varchar' },
          { label: 'VARCHAR2', value: 'varchar2' },
          { label: 'TEXT', value: 'text' },
          { label: 'CLOB', value: 'clob' }
        ],
        '日期时间类型': [
          { label: 'DATE', value: 'date' },
          { label: 'TIME', value: 'time' },
          { label: 'TIMESTAMP', value: 'timestamp' },
          { label: 'DATETIME', value: 'datetime' }
        ],
        '二进制类型': [
          { label: 'BLOB', value: 'blob' },
          { label: 'BINARY', value: 'binary' },
          { label: 'VARBINARY', value: 'varbinary' },
          { label: 'IMAGE', value: 'image' }
        ],
        '其他类型': [
          { label: 'BOOLEAN', value: 'boolean' },
          { label: 'BIT', value: 'bit' }
        ]
      };
    default:
      return {
        '通用类型': [
          { label: 'INTEGER', value: 'integer' },
          { label: 'TEXT', value: 'text' },
          { label: 'VARCHAR', value: 'varchar' },
          { label: 'DATE', value: 'date' },
          { label: 'TIMESTAMP', value: 'timestamp' },
          { label: 'DECIMAL', value: 'decimal' },
          { label: 'BOOLEAN', value: 'boolean' }
        ]
      };
  }
});

// 自增标签根据数据库类型不同
const autoIncrementLabel = computed(() => {
  switch (props.databaseType) {
    case 'postgresql':
      return 'Serial';
    case 'sqlserver':
      return 'Identity';
    case 'dameng':
      return '标识列';
    default:
      return '自增';
  }
});

// 是否有已存在的自增列
const hasAutoIncrement = computed(() => {
  return localColumns.value.some(col => col.autoIncrement);
});

// 添加列
const addColumn = () => {
  // 根据数据库类型创建默认列
  const newColumn = createDefaultColumn();
  
  // 添加到本地columns
  localColumns.value.push(newColumn);
  
  // 发送添加事件 - 这会通知父组件添加列
  emit('add', newColumn);
  
  // 选中新添加的列
  selectedColumnIndex.value = localColumns.value.length - 1;
};

// 根据数据库类型创建默认列
const createDefaultColumn = () => {
  const baseColumn = {
    name: '',
    notNull: false,
    primaryKey: false,
    defaultValue: '',
    comment: ''
  };
  
  switch (props.databaseType) {
    case 'mysql':
      return {
        ...baseColumn,
        type: 'varchar',
        length: '255',
        autoIncrement: false
      };
    case 'postgresql':
      return {
        ...baseColumn,
        type: 'varchar',
        length: '255'
      };
    case 'sqlite':
      return {
        ...baseColumn,
        type: 'text',
        autoIncrement: false
      };
    case 'sqlserver':
      return {
        ...baseColumn,
        type: 'nvarchar',
        length: '255',
        identity: false
      };
    default:
      return {
        ...baseColumn,
        type: 'varchar',
        length: '255'
      };
  }
};

// 确认删除列
const confirmRemoveColumn = (index) => {
  const columnName = localColumns.value[index].name || `列 #${index + 1}`;
  
  ElMessageBox.confirm(`确定要删除列 "${columnName}" 吗?`, '确认删除', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 发送删除事件
    emit('remove', index);
  }).catch(() => {
    // 用户取消操作
  });
};

// 处理数据类型变化
const handleDataTypeChange = (newType, columnIndex) => {
  const column = localColumns.value[columnIndex];
  
  // 根据新类型调整其他属性
  if (!needsLength(newType)) {
    column.length = '';
  } else if (!column.length) {
    // 设置默认长度
    if (['varchar', 'char', 'nvarchar', 'nchar', 'varchar2'].includes(newType)) {
      column.length = '255';
    } else if (['int', 'integer', 'bigint', 'smallint'].includes(newType)) {
      column.length = props.databaseType === 'mysql' ? '11' : '';
    } else if (['decimal', 'numeric', 'number'].includes(newType)) {
      column.length = '10';
      
      // 对于达梦数据库，设置精度和刻度
      if (props.databaseType === 'dameng') {
        column.precision = 10;
        column.scale = 2;
      }
    }
  }
  
  // 特殊处理达梦数据库字符类型
  if (props.databaseType === 'dameng' && isCharType(newType)) {
    // 确保语义类型字段存在
    if (!column.semanticType) {
      column.semanticType = 'BYTE';
    }
  }
  
  // PostgreSQL特殊处理
  if (props.databaseType === 'postgresql') {
    if (isSerialType(newType)) {
      column.primaryKey = true;
      column.notNull = true;
    }
  } else {
    // 其他数据库类型的处理
    // 如果新类型不支持自增，取消自增
    if (column.autoIncrement && !canBeAutoIncrement(newType)) {
      column.autoIncrement = false;
    }
  }
  
  handleColumnChange();
};

// 处理主键变化
const handlePrimaryKeyChange = (columnIndex) => {
  const column = localColumns.value[columnIndex];
  
  // 如果设为主键，自动设为非空
  if (column.primaryKey) {
    column.notNull = true;
    
    // 如果类型支持自增，询问是否设为自增
    if (props.databaseType !== 'postgresql' && 
        canBeAutoIncrement(column.type) && 
        !hasAutoIncrement.value) {
      ElMessageBox.confirm('是否将该主键列设为自增?', '设置自增', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'info'
      }).then(() => {
        column.autoIncrement = true;
        handleColumnChange();
      }).catch(() => {
        // 用户选择不设为自增
        handleColumnChange();
      });
    } else {
      handleColumnChange();
    }
  } else {
    handleColumnChange();
  }
};

// 处理自增变化
const handleAutoIncrementChange = (columnIndex) => {
  const column = localColumns.value[columnIndex];
  
  // 如果设为自增，确保是主键且非空
  if (column.autoIncrement) {
    column.notNull = true;
    
    // 关闭其他列的自增
    localColumns.value.forEach((col, idx) => {
      if (idx !== columnIndex && col.autoIncrement) {
        col.autoIncrement = false;
      }
    });
    
    // 如果不是主键，询问是否设为主键
    if (!column.primaryKey) {
      ElMessageBox.confirm('自增列通常是主键，是否将该列设为主键?', '设置主键', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'info'
      }).then(() => {
        // 取消其他列的主键
        localColumns.value.forEach((col, idx) => {
          if (idx !== columnIndex && col.primaryKey) {
            col.primaryKey = false;
          }
        });
        
        column.primaryKey = true;
        handleColumnChange();
      }).catch(() => {
        // 用户选择不设为主键
        handleColumnChange();
      });
    } else {
      handleColumnChange();
    }
  } else {
    handleColumnChange();
  }
};

// 发送列变更事件
const handleColumnChange = () => {
  // 处理达梦特有属性
  if (props.databaseType === 'dameng') {
    localColumns.value.forEach(col => {
      // 确保字符类型有语义设置
      if (checkCharType(col.type) && !col.semanticType) {
        col.semanticType = 'BYTE'; // 默认字节语义
      }
    });
  }
  
  emit('update', [...localColumns.value]);
};

// 类型是否需要长度
const needsLength = (type) => {
  if (!type) return false;
  
  const typesNeedLength = {
    mysql: ['varchar', 'char', 'int', 'tinyint', 'smallint', 'mediumint', 'bigint', 
            'decimal', 'float', 'double', 'bit', 'binary', 'varbinary'],
    postgresql: ['varchar', 'character', 'char', 'decimal', 'numeric'],
    sqlite: ['varchar', 'char'],
    sqlserver: ['varchar', 'nvarchar', 'char', 'nchar', 'binary', 'varbinary',
                'decimal', 'numeric', 'float'],
    dameng: ['varchar', 'varchar2', 'char', 'binary', 'varbinary', 'decimal', 'number', 'float', 'double']
  };
  
  return (typesNeedLength[props.databaseType] || []).includes(type);
};

// 类型是否需要值列表
const needsValues = (type) => {
  if (!type) return false;
  
  const typesNeedValues = {
    mysql: ['enum', 'set'],
    sqlserver: [],
    postgresql: [],
    sqlite: [],
    dameng: []
  };
  
  return (typesNeedValues[props.databaseType] || []).includes(type);
};

// 类型是否可以自增
const canBeAutoIncrement = (type) => {
  if (!type) return false;
  
  const autoIncrementTypes = {
    mysql: ['tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'double', 'decimal'],
    sqlite: ['integer'],
    sqlserver: ['int', 'bigint', 'smallint', 'tinyint'],
    dameng: ['int', 'integer', 'bigint', 'smallint', 'tinyint', 'number']
  };
  
  return (autoIncrementTypes[props.databaseType] || []).includes(type);
};

// 是否为PostgreSQL的serial类型
const isSerialType = (type) => {
  if (!type) return false;
  
  if (props.databaseType === 'postgresql') {
    return ['serial', 'smallserial', 'bigserial'].includes(type);
  } else if (props.databaseType === 'dameng') {
    // DaMeng doesn't have specific serial types like PostgreSQL
    return false;
  }
  
  return false;
};

// 选择列
const selectColumn = (index) => {
  selectedColumnIndex.value = index;
  
  // 调试：输出列信息
  const column = localColumns.value[index];
  console.log(`[DEBUG] 选中列 ${index}:`, {
    name: column.name,
    type: column.type,
    rawLength: column.length,
    displayLength: column.lengthDisplay || parseColumnLength(column),
    rawComment: column.comment,
    displayComment: parseColumnComment(column),
    semanticType: column.semanticType,
    rawInfo: column.rawInfo
  });
};

// 向上移动选中的列
const moveColumnUp = () => {
  if (selectedColumnIndex.value > 0) {
    // 交换当前列和上一列
    const temp = localColumns.value[selectedColumnIndex.value];
    localColumns.value[selectedColumnIndex.value] = localColumns.value[selectedColumnIndex.value - 1];
    localColumns.value[selectedColumnIndex.value - 1] = temp;
    
    // 更新选择的索引
    selectedColumnIndex.value--;
    
    // 通知父组件数据已更新
    handleColumnChange();
  }
};

// 向下移动选中的列
const moveColumnDown = () => {
  if (selectedColumnIndex.value !== -1 && selectedColumnIndex.value < localColumns.value.length - 1) {
    // 交换当前列和下一列
    const temp = localColumns.value[selectedColumnIndex.value];
    localColumns.value[selectedColumnIndex.value] = localColumns.value[selectedColumnIndex.value + 1];
    localColumns.value[selectedColumnIndex.value + 1] = temp;
    
    // 更新选择的索引
    selectedColumnIndex.value++;
    
    // 通知父组件数据已更新
    handleColumnChange();
  }
};

// 判断是否为字符类型
const isCharType = (type) => {
  return checkCharType(type);
};

// 获取列的显示长度
const getColumnDisplayLength = (column) => {
  if (needsLength(column.type)) {
    if (column.length) {
      return column.length;
    } else if (['varchar', 'char', 'nvarchar', 'nchar'].includes(column.type)) {
      return '255';
    } else if (['int', 'integer', 'bigint', 'smallint'].includes(column.type)) {
      return props.databaseType === 'mysql' ? '11' : '';
    } else if (['decimal', 'numeric'].includes(column.type)) {
      return '10,2';
    }
  }
  return '-';
};
</script>

<style scoped>
.table-columns-panel {
  padding: 16px 0;
}

.table-wrapper {
  overflow: hidden;
  width: 100%;
}

/* 设置表格为固定宽度而不是自适应 */
table {
  width: auto;
  border-collapse: separate;
  border-spacing: 0;
}

/* 固定表头 */
thead th {
  position: sticky;
  top: 0;
  z-index: 20;
}

/* 拖动手柄样式 */
.drag-handle {
  cursor: move; /* fallback for old browsers */
  cursor: -webkit-grab;
  cursor: grab;
  touch-action: none;
}

.drag-handle:active {
  cursor: -webkit-grabbing;
  cursor: grabbing;
}

.drag-handle:hover div {
  background-color: #9ca3af;
}

/* 拖拽时禁用表单控件交互 */
:global(.sorting-active) :deep(.el-input__wrapper),
:global(.sorting-active) :deep(.el-checkbox),
:global(.sorting-active) :deep(.el-select),
:global(.sorting-active) :deep(.el-button) {
  pointer-events: none !important;
}

/* 确保Vue样式不干扰拖拽 */
:deep(.el-checkbox) {
  width: 100%;
  display: flex;
  justify-content: center;
}

:deep(.el-input__wrapper) {
  box-shadow: none !important;
  width: 100%;
}

:deep(.el-input__wrapper:hover) {
  border-color: #dcdfe6;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
}

:deep(.data-type-select) {
  min-width: 12rem;
  width: 100%;
}

:deep(.el-select-dropdown) {
  min-width: 200px !important;
  z-index: 9999 !important;
}

:deep(.el-select-dropdown__list) {
  width: auto !important;
  min-width: 200px !important;
}
</style> 